<template>
  <div class="tour-send-container">
    <!-- 顶部搜索栏 -->
    <div class="header-search">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索已发布的跟团游"
        prefix-icon="el-icon-search"
        class="search-input"
      ></el-input>
    </div>
    
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="title">已发布跟团游列表</h1>
      <p class="subtitle">浏览当前旅行社发布的所有已审核通过的跟团游信息</p>
    </div>
    
    <!-- 跟团游列表 -->
    <div class="tour-list" v-loading="loading">
      <div 
        class="tour-card" 
        v-for="tour in filteredTours" 
        :key="tour.groupTourId"
      >
        <!-- 左上角状态标签 -->
        <div class="status-tag" :class="getStatusClass(tour.progressStatus)">
          {{ getStatusText(tour.progressStatus) }}
        </div>
        
        <div class="tour-cover">
          <img :src="getFirstImage(tour)" alt="跟团游封面">
        </div>
        
        <div class="tour-info">
          <h3 class="tour-name">{{ tour.groupTourName }}</h3>
          
          <div class="meta-info">
            <span><i class="el-icon-location"></i> {{ tour.scenicAreaName }}</span>
            <span><i class="el-icon-date"></i> {{ formatDate(tour.releaseDate) }}</span>
          </div>
          
          <div class="price-section">
            <span class="price">¥{{ tour.groupTourPrice }}</span>/人起
          </div>
          
          <div class="interaction">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-view"
              @click="viewDetails(tour)"
            >查看详情</el-button>
            
            <div class="favorite-count">
              <i class="el-icon-star-on"></i>
              <span>{{ tour.favoriteCount || 0 }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        :page-sizes="[5, 10, 20]"
        :page-size="pageSize"
        :total="totalTours"
        layout="total, prev, pager, next, jumper"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      ></el-pagination>
    </div>

    <!-- 无数据提示 -->
    <div v-if="!loading && filteredTours.length === 0" class="no-data">
      <el-empty description="暂无已发布的跟团游"></el-empty>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  data() {
    return {
      searchKeyword: '',
      currentPage: 1,
      pageSize: 10,
      totalTours: 0,
      loading: false,
      tours: [],
      agencyId: null,
      loginId: null
    }
  },
  computed: {
    filteredTours() {
      // 过滤已审核通过的跟团游
      let result = this.tours.filter(tour => 
        tour.auditStatus === '通过'
      )
      
      // 搜索过滤
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase()
        result = result.filter(tour => 
          (tour.groupTourName && tour.groupTourName.toLowerCase().includes(keyword)) ||
          (tour.scenicAreaName && tour.scenicAreaName.toLowerCase().includes(keyword)) ||
          (tour.province && tour.province.toLowerCase().includes(keyword)) ||
          (tour.city && tour.city.toLowerCase().includes(keyword))
        )
      }
      
      this.totalTours = result.length
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return result.slice(start, end)
    }
  },
  methods: {
    // 获取封面图片
    getFirstImage(tour) {
      // 如果有图片链接数组
      if (tour.images && tour.images.length > 0) {
        return tour.images[0]
      }
      // 如果没有图片，使用默认图片
      return 'https://picsum.photos/600/400?random=' + Math.random()
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`
    },
    
    // 获取状态样式类
    // 修改getStatusClass方法
    getStatusClass(status) {
      switch(status) {
        case '未开始': return 'status-not-started'
        case '报名中': return 'status-recruiting'
        case '报名截止': return 'status-registration-closed'
        case '进行中': return 'status-in-progress'
        case '已结束': return 'status-completed'
        default: return 'status-not-started'
      }
    },

    // 方法
    getStatusText(status) {
      return status || '未开始'
    },
    

    // 查看详情
    viewDetails(tour) {
      this.$router.push({
        name: 'GroupTourAudit', // 使用路由名称而不是组件名称
        params: { id: tour.groupTourId }
      })
    },
        
    // 分页变化
    handlePageChange(page) {
      this.currentPage = page
    },
    
    // 每页数量变化
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
    },
    
    // 获取旅行社ID
// 获取旅行社ID
    async getAgencyId() {
      try {
        // 从localStorage获取loginId
        this.loginId = localStorage.getItem('loginId')
        if (!this.loginId) {
          ElMessage.error('未获取到用户ID，请重新登录')
          return null
        }
        
        // 根据loginId查询旅行社ID
        const response = await axios.get(`http://localhost:8080/mw/travelAgency/byLoginId/${this.loginId}`)
        
        if (response.data && response.data.travelAgencyId) {
          return response.data.travelAgencyId
        } else {
          ElMessage.error('未找到对应的旅行社信息')
          return null
        }
      } catch (error) {
        console.error('获取旅行社ID失败:', error)
        ElMessage.error('获取旅行社ID失败')
        return null
      }
    },
    
    // 获取跟团游数据
    async fetchGroupTours() {
      this.loading = true
      this.agencyId = await this.getAgencyId()
      
      if (!this.agencyId) {
        this.loading = false
        return
      }
      
      try {
        // 获取所有跟团游数据
        const response = await axios.get(`/mw/groupToursByAgency/${this.agencyId}`)
        const tours = response.data || []
        
        // 为每个跟团游获取图片和收藏数
        for (const tour of tours) {
          try {
            // 获取图片
            const imgRes = await axios.get(`/mw/travelAuditImages/${tour.groupTourId}`)
            tour.images = imgRes.data.map(img => img.groupTourImageLink)
            
            // 获取收藏数
            const favRes = await axios.get('/mw/getFavoriteCount', {
              params: { groupTourId: tour.groupTourId }
            })
            tour.favoriteCount = favRes.data.count || 0
          } catch (e) {
            console.error('获取图片或收藏数失败:', e)
            tour.images = []
            tour.favoriteCount = 0
          }
        }
        
        this.tours = tours
        this.totalTours = tours.filter(t => t.auditStatus === '通过').length
      } catch (error) {
        console.error('获取跟团游数据失败:', error)
        ElMessage.error('获取跟团游数据失败')
        this.tours = []
      } finally {
        this.loading = false
      }
    }
  },
  mounted() {
    this.fetchGroupTours()
  }
}
</script>

<style scoped>
.tour-send-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header-search {
  margin-bottom: 20px;
}

.search-input {
  width: 100%;
  height: 40px;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.title {
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

.subtitle {
  font-size: 16px;
  color: #666;
  margin-top: 10px;
}

.tour-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.tour-card {
  position: relative;
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease;
}

.tour-card:hover {
  transform: translateY(-5px);
}

.status-tag {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 2;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  color: white;
}

.status-not-started {
  background-color: #67C23A; /* 绿色 - 未开始 */
}

.status-recruiting {
  background-color: #409EFF; /* 蓝色 - 报名中 */
}

.status-registration-closed {
  background-color: #E6A23C; /* 橙色 - 报名截止 */
}

.status-in-progress {
  background-color: #9254de; /* 紫色 - 进行中 */
}

.status-completed {
  background-color: #909399; /* 灰色 - 已结束 */
}

.tour-cover {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.tour-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.tour-cover:hover img {
  transform: scale(1.1);
}

.tour-info {
  padding: 15px;
}

.tour-name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  height: 50px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.meta-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 15px;
  color: #666;
  font-size: 14px;
}

.meta-info span {
  display: flex;
  align-items: center;
}

.price-section {
  margin-bottom: 15px;
}

.price-section .price {
  font-size: 22px;
  font-weight: bold;
  color: #f56c6c;
}

.interaction {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.favorite-count {
  display: flex;
  align-items: center;
  color: #E6A23C;
  font-size: 14px;
}

.favorite-count i {
  margin-right: 5px;
  font-size: 16px;
}

.pagination {
  margin-top: 30px;
  text-align: center;
}

.no-data {
  margin-top: 50px;
  text-align: center;
}
</style>